//
//  AlbumViewController.m
//  LoveOfPet
//
//  Created by 芦彬 on 15/11/17.
//  Copyright © 2015年 孔维. All rights reserved.
//

#import "AlbumViewController.h"
#import "LuBDefine.h"
#import "LBAFNetworking.h"
#import "Album.h"
#import "AlbumCollectionViewCell.h"
#import "LuBinCollection.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"

#import "CoreDataManager.h"
#import "LuBinCollection.h"
#import <SVProgressHUD.h>


@interface AlbumViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain)UICollectionView *collectionView;

@property (nonatomic, retain)NSMutableArray *albumArray;

@property (nonatomic, retain)UIImageView *bgImageView;

@property (nonatomic, retain)LuBinCollection *luBinCollection;

@property (nonatomic, retain)CoreDataManager *coreDataManger;

@property (nonatomic, assign)BOOL exsit;

@end

@implementation AlbumViewController

- (void)dealloc{
    [_ppid release];
    [_photo_des release];
    [_collectionView release];
    [_bgImageView release];
    [_albumArray release];
    [_luBinCollection release];
    [_coreDataManger release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.albumArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.coreDataManger = [CoreDataManager shareCoreDataManager];
    [self downloadData];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"2.jpg"] forBarMetrics:UIBarMetricsDefaultPrompt];
    [self createAlbumViewController];
    // Do any additional setup after loading the view.
}

- (void)downloadData{
    NSString *url = [NSString stringWithFormat:@"http://api.epetbar.com/gutouv2/story.html?do=storyitem&ppid=%@&develop=0",self.ppid];
    self.bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, CWIDTH, CHEIGHT - 40)];
    [self.view addSubview:_bgImageView];
    [_bgImageView release];
    [LBNetWork handleGETWithUrlString:url parameters:nil showHuD:YES onView:self.view successfulBlock:^(id responseObject) {
        NSArray *tempArray = [NSArray arrayWithArray:[[responseObject objectForKey:@"data"] objectForKey:@"content"]];
        for (NSDictionary *dic in tempArray) {
            if ([ [NSString stringWithFormat:@"%@",[dic objectForKey:@"type"]] isEqualToString:@"1"]) {
                Album *album = [Album albumWithDictionary:dic];
                if ([album.width isEqual:@"1"]) {
                }else{
                    [self.albumArray addObject:album];
                    NSURL *bgurl = [NSURL URLWithString:[self.albumArray[0] photo]];
                    [self.bgImageView sd_setImageWithURL:bgurl placeholderImage:[UIImage imageNamed:@"zhanweitu.jpg"]];
                }
            }
        }
        [self.collectionView reloadData];
        } failureBlock:^(NSError *error) {
        NSLog(@"失败");
    }];
}

-(void)createAlbumViewController{
    self.navigationItem.title = self.photo_des;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0];
   
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
    [visualEffectView setFrame:CGRectMake(0, 0, CWIDTH, CHEIGHT - 40)];
    [self.view addSubview:visualEffectView];
    [visualEffectView release];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    if (CHEIGHT == 480) {
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CHEIGHT / 8, CWIDTH, 360) collectionViewLayout:layout];
    }else{
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CHEIGHT / 6, CWIDTH, 360) collectionViewLayout:layout];
    }
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0];
    [self.view addSubview:_collectionView];
    [_collectionView release];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[AlbumCollectionViewCell class] forCellWithReuseIdentifier:@"albumCell"];
    
    UIButton *collectionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    collectionBtn.frame = CGRectMake(0, CHEIGHT - 40, CWIDTH, 40);
    collectionBtn.backgroundColor = [UIColor redColor];
    [collectionBtn setTitle:@"收藏" forState:UIControlStateNormal];
    [collectionBtn addTarget:self action:@selector(collectionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:collectionBtn];

}

- (void)collectionBtnAction:(UIButton *)button{
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"LuBinCollection"];
    NSArray *resultArray = [_coreDataManger.managedObjectContext executeFetchRequest:request error:nil];
    for (LuBinCollection *collection in resultArray) {
        if ([collection.ppid isEqualToString:self.ppid]) {
            self.exsit = YES;
            break;
        }
    }
    if (self.exsit) {
        [SVProgressHUD show];
        [SVProgressHUD showInfoWithStatus:@"已收藏"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }else{
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"LuBinCollection" inManagedObjectContext:self.coreDataManger.managedObjectContext];
        LuBinCollection *collection = [[LuBinCollection alloc]initWithEntity:entity insertIntoManagedObjectContext:_coreDataManger.managedObjectContext];
        collection.ppid = self.ppid;
        collection.photo_des = self.photo_des;
        [_coreDataManger saveContext];
        [SVProgressHUD show];
        [SVProgressHUD showInfoWithStatus:@"收藏成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.albumArray.count;
}

- (CGSize )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat widths = [[(Album *)self.albumArray[indexPath.row] width] floatValue];
    CGFloat heights = [[(Album *)self.albumArray[indexPath.row] height] floatValue];
    CGFloat number = widths / heights;
    CGFloat wid = number * 360;
    return CGSizeMake(wid, 360);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.albumArray.count) {
        AlbumCollectionViewCell *albumCollectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"albumCell" forIndexPath:indexPath];
        albumCollectionViewCell.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0];
        albumCollectionViewCell.album = self.albumArray[indexPath.row];
        
        CATransition *anim = [CATransition animation];
        anim.type = @"cube"; // 动画过渡类型
        anim.subtype = kCATransitionFromTop; // 动画过渡方向
        anim.duration = 1; // 动画持续1s
        // 代理，动画执行完毕后会调用delegate的animationDidStop:finished:
        anim.delegate = self;
        [albumCollectionViewCell.layer addAnimation:anim forKey:@"key"];
        
        return albumCollectionViewCell;
    }else{
        return 0;
    }
}

//页面边缘手势导航栏变不透明,tableView布局发生变化
- (void)viewDidAppear:(BOOL)animated{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"2.jpg"] forBarMetrics:UIBarMetricsCompact];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
